package br.com.ir.tcc.geco.web;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.NestedNullException;
import org.apache.commons.lang.StringUtils;
import org.json.JSONArray;
import org.json.JSONObject;

public class WebController {
	
	public static final String ORDER_BY = "sidx";
	public static final String ORDER_DIR = "sord";
	public static final String ROWS = "rows";
	public static final String PAGE = "page";
	public static final String TOTAL = "total";
	public static final String RECORDS = "records";
	public static final String SEARCH_FIELD = "sField";
	public static final String SEARCH_VALUE = "sValue";

	@SuppressWarnings("unchecked")
	protected List buildRows(List list, String... propertyNames) {
		
		if (propertyNames == null || propertyNames.length == 0)
			throw new IllegalArgumentException("Property list not found.");
		
		List<JSONObject> jsonObjects = new ArrayList<JSONObject>();
		
		try {
			
			for (Object object : list) {
				
				List values = new ArrayList();
				for (String name : propertyNames) {
					
					Object value = null;
					
					try {
						value = BeanUtils.getProperty(object, name);
					} catch (NestedNullException e) {/*Considerar valor nulo*/}
					
					values.add(value);
				}
				
				JSONObject jsonObject = new JSONObject();
				jsonObject.put("id", BeanUtils.getProperty(object, "id"));
				jsonObject.put("cell", new JSONArray(values));
				jsonObjects.add(jsonObject);
			}
			
		} catch (NestedNullException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
		return jsonObjects;
		
	}
	
	protected String getOrderBy(HttpServletRequest request){
		String orderBy = request.getParameter(ORDER_BY);
		String orderDir = request.getParameter(ORDER_DIR);
		return StringUtils.isNotEmpty(orderBy) ? orderBy + " " + orderDir : null;
	}
}
